package com.example.yls.demoa;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements IOnDataChangeListener {

    private Button btnAdd;
    private ListView listView;
    private ArrayList<Student> studentList = new ArrayList<>();
    private StuAdapter adapter;
    private EditText edtSearch;
    private Button btnSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findView();
//        initStudentList();
//
        adapter = new StuAdapter(MainActivity.this,studentList,MainActivity.this);
        readDataFromDB();
        listView.setAdapter(adapter);


        //点击添加学生

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent,2001);
            }
        });


        //优化搜索
        edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String key = edtSearch.getText().toString();
                searchFromDB(key);
            }
        });

        //搜索学生
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = edtSearch.getText().toString();
                searchFromDB(key);
            }
        });
    }

    //搜索学生
    private void searchFromDB(String key) {
        Uri uri = Uri.parse("content://com.gdcp.student1/student");
        String where = "name like '%"+key+"%' OR stuno like '%"+key+"%'" +
                " OR age like '%"+key+"%'" ;
        //避免重复添加
        studentList.clear();
        Cursor cursor = getContentResolver().query(uri,null,where,
                null,null);
        if (cursor!=null && cursor.getCount()>0){
            for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student student = new Student(stuno,name,age);
                studentList.add(student);
            }
        }

        adapter.notifyDataSetChanged();
    }

    private void findView() {
        listView = findViewById(R.id.listview);
        btnAdd = findViewById(R.id.btn_add);
        btnSearch = findViewById(R.id.btn_search);
        edtSearch = findViewById(R.id.edt_search);

        //编辑学生  点击学生修改数据
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                //将点击的第几个学生 取出来
                Student student = studentList.get(i);
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,EditActivity.class);
                intent.putExtra("STUNO",student.getStuno());
                intent.putExtra("NAME",student.getName());
                intent.putExtra("AGE",student.getAge());
                startActivityForResult(intent,3001);
                Toast.makeText(MainActivity.this,
                        "你点击了学号为"+student.getStuno()+"  叫"+student.getName()+
                                " 年龄"+student.getAge(),Toast.LENGTH_SHORT).show();

            }
        });
    }




//    //初始化学生
//    private void initStudentList() {
//        studentList.add(new Student("17001","张三",18));
//        studentList.add(new Student("17002","李爱",18));
//        studentList.add(new Student("17003","王老五",18));
//        studentList.add(new Student("17004","赵晓柳",18));
//
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode==1001){
            String stuno = data.getStringExtra("STUNO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);
            Student student = new Student(stuno,name,age);
            addStudentToDB(student);
        }else if(resultCode ==4001){
            String stuno = data.getStringExtra("STUNO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);
            Student student = new Student(stuno,name,age);
            updateStudentToDB(student);
        }
    }

    //更新学生数据  编辑学生
    private void updateStudentToDB(Student student) {
        Uri uri = Uri.parse("content://com.gdcp.student1/student");
        String where ="stuno ='"+student.getStuno()+"' or name='"+student.getName()+"'" +
                "or age='"+student.getAge()+"' ";
        ContentValues values = new ContentValues();
        values.put("stuno",student.getStuno());
        values.put("name",student.getName());
        values.put("age",student.getAge());
        int i = getContentResolver().update(uri,values,where,null);

        Toast.makeText(MainActivity.this,"更新了"+i+"条数据"
                ,Toast.LENGTH_SHORT).show();
        readDataFromDB();
    }

    //插入学生数据
    private void addStudentToDB(Student student) {
//        studentList.clear();
        Uri uri = Uri.parse("content://com.gdcp.student1/student");
        ContentValues values = new ContentValues();
        values.put("stuno",student.getStuno());
        values.put("name",student.getName());
        values.put("age",student.getAge());
        getContentResolver().insert(uri,values);
        readDataFromDB();

    }
    //从数据库读取学生列表   读取学生
    private void readDataFromDB() {

        Uri uri = Uri.parse("content://com.gdcp.student1/student");
        //避免重复添加
        studentList.clear();

        Cursor cursor = getContentResolver().query(uri,null,null,null,null);

//        如果cursor为空
        if(cursor != null && cursor.getCount() > 0){
            //遍历读取数据
            for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student student = new Student(stuno,name ,age);
                studentList.add(student);
            }
        }
        //通知界面更新
        adapter.notifyDataSetChanged();

    }

    //删除学生
    @Override
    public void del(Student student) {
        Uri uri = Uri.parse("content://com.gdcp.student1/student");
        String where ="stuno ='"+student.getStuno()+"'";
        int i = getContentResolver().delete(uri,where,null);
        readDataFromDB();
    }
}
